package com.example.asapp.aspect;

import com.example.asapp.annotation.HasLogin;
import com.example.asapp.annotation.HasRole;
import com.example.asapp.base.BaseService;
import com.example.asapp.exception.AuthUnexpectException;
import com.example.asapp.user.detail.Detail;
import com.example.asapp.user.detail.DetailDao;
import com.example.asapp.user.role.Role;
import com.example.asapp.user.role.RoleDao;
import com.example.asapp.util.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/*
    @auth fbz
    @date 2021/5/26/10:35
*/

@Component
@Aspect
@Slf4j
public class HasLoginAspect {

    @Autowired
    BaseService baseService;

    @Pointcut("@annotation(com.example.asapp.annotation.HasLogin)")
    void pointcut() {

    }

    @Before("pointcut() && @annotation(hasLogin)")
    public void before(JoinPoint joinPoint, HasLogin hasLogin) throws AuthUnexpectException {
        if(baseService.getLogin()){
            log.info("user({}) has login",baseService.getUserId());
        }else {
            throw new AuthUnexpectException();
        }
    }

//    @Around("pointcut() && @annotation(hasLogin)")
//    public HashMap<String,Object> advice(JoinPoint joinPoint, HasLogin hasLogin) throws AuthUnexpectException {
//        HashMap<String,Object> map=new HashMap<>();
//        String token=request.getHeader("token");
//        String userId=(String) redisService.get(token);
//
//        log.info("login user id is:{}",userId);
//        Detail detail=detailDao.findById(userId).get();
//        map.put("detail",detail);
//        map.put("login",true);
//        map.put("token",token);
//        List<String> roleList=detail.getRoleList().stream().map(e->{
//            return e.getValue();
//        }).collect(Collectors.toList());
//        map.put("roleList",roleList);
//        map.put("options",getOptions());
//        return map;
//    }
//
//    private HashMap<String,Object> getOptions(){
//        HashMap<String,Object> map=new HashMap<>();
//        map.put("roleOptions",roleDao.findAll());
//        return map;
//    }


}
